package com.pokermind.dse.tcp.service;

import com.pokermind.dse.tcp.protocol.ProtocolMessage;
import com.pokermind.dse.tcp.util.ResponseWrapper;
import com.pokermind.model.dto.AuthRequest;
import com.pokermind.model.dto.AuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 认证服务
 * 
 * 处理API Key认证逻辑
 * 
 * @author PokerMind Team
 */
@Service
public class AuthService {
    
    private static final Logger logger = LoggerFactory.getLogger(AuthService.class);
    
    /**
     * 有效的API Key配置
     * TODO: 生产环境应从数据库或配置中心加载
     */
    private static final Map<String, ClientConfig> VALID_API_KEYS = new HashMap<>();
    
    static {
        // 测试环境默认Key
        VALID_API_KEYS.put("pk_test_demo00000000000000000000000000000000", 
            new ClientConfig("demo_client", "Demo Client", Arrays.asList("hand_management", "ai_analysis", "system_query"), createDefaultQuota()));
        
        // 可以添加更多测试Key
        VALID_API_KEYS.put("pk_test_a3f9c2b4d5e67890abcd1234ef567890",
            new ClientConfig("client_001", "Test Client 001", Arrays.asList("hand_management", "ai_analysis"), createDefaultQuota()));
    }
    
    /**
     * 处理认证请求
     */
    public ProtocolMessage handleAuth(ProtocolMessage request) {
        long startTime = System.currentTimeMillis();
        
        try {
            // 提取请求数据
            AuthRequest authRequest = ResponseWrapper.extractBusinessData(request, AuthRequest.class);
            
            logger.info("[AUTH] Authenticating: apiKey={}, clientVersion={}, clientName={}", 
                maskApiKey(authRequest.getApiKey()), 
                authRequest.getClientVersion(), 
                authRequest.getClientName());
            
            // 验证API Key
            String apiKey = authRequest.getApiKey();
            if (apiKey == null || apiKey.trim().isEmpty()) {
                return createAuthErrorResponse(request, "API Key不能为空");
            }
            
            ClientConfig clientConfig = VALID_API_KEYS.get(apiKey);
            if (clientConfig == null) {
                logger.warn("[AUTH] Invalid API Key: {}", maskApiKey(apiKey));
                return createAuthErrorResponse(request, "无效的API Key");
            }
            
            // 生成会话信息
            String sessionId = generateSessionId();
            
            // 构造响应
            AuthResponse authResponse = AuthResponse.builder()
                .sessionId(sessionId)
                .clientId(clientConfig.getClientId())
                .permissions(clientConfig.getPermissions())
                .quota(clientConfig.getQuota())
                .authenticatedAt(System.currentTimeMillis())
                .build();
            
            long duration = System.currentTimeMillis() - startTime;
            logger.info("[AUTH] Authentication successful: clientId={}, sessionId={}, time={}ms", 
                clientConfig.getClientId(), sessionId, duration);
            
            return ResponseWrapper.createSuccessResponse(request, "authenticated", authResponse);
            
        } catch (Exception e) {
            logger.error("[AUTH] Authentication failed: {}", e.getMessage(), e);
            return ResponseWrapper.createErrorResponse(request, 5000, "认证处理失败: " + e.getMessage());
        }
    }
    
    /**
     * 创建认证错误响应
     */
    private ProtocolMessage createAuthErrorResponse(ProtocolMessage request, String errorMessage) {
        Map<String, Object> errorData = new HashMap<>();
        errorData.put("error", "authentication_failed");
        errorData.put("detail", errorMessage);
        return ResponseWrapper.createResponse(request, 4010, "authentication failed", errorData);
    }
    
    /**
     * 生成会话ID
     */
    private String generateSessionId() {
        return "sess_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
    }
    
    /**
     * 掩码API Key
     */
    private String maskApiKey(String apiKey) {
        if (apiKey == null || apiKey.length() < 12) {
            return "***";
        }
        int len = apiKey.length();
        return apiKey.substring(0, 8) + "***" + apiKey.substring(len - 4);
    }
    
    /**
     * 创建默认配额
     */
    private static Map<String, Object> createDefaultQuota() {
        Map<String, Object> quota = new HashMap<>();
        quota.put("max_hands_per_day", 1000);
        quota.put("max_ai_calls_per_day", 500);
        quota.put("max_connections", 5);
        quota.put("rate_limit_per_second", 10);
        return quota;
    }
    
    /**
     * 客户端配置
     */
    private static class ClientConfig {
        private final String clientId;
        private final String clientName;
        private final List<String> permissions;
        private final Map<String, Object> quota;
        
        public ClientConfig(String clientId, String clientName, List<String> permissions, Map<String, Object> quota) {
            this.clientId = clientId;
            this.clientName = clientName;
            this.permissions = permissions;
            this.quota = quota;
        }
        
        public String getClientId() {
            return clientId;
        }
        
        public String getClientName() {
            return clientName;
        }
        
        public List<String> getPermissions() {
            return permissions;
        }
        
        public Map<String, Object> getQuota() {
            return quota;
        }
    }
}



